package com.jwong.test;

import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.ExecListener;
import io.fabric8.kubernetes.client.dsl.ExecWatch;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.CountDownLatch;

public class ExecExample {

    public static void main(String[] args) throws UnsupportedEncodingException {
        String namespace = "default";
        String podName = "mysql-slave-7bc44964bb-fd2fr";

        try (
                KubernetesClient client = new DefaultKubernetesClient();
                ExecWatch watch = newExecWatch(client, namespace, podName)
        ){}
/*        {
            Thread.sleep(10 * 1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }

    private static ExecWatch newExecWatch(KubernetesClient client, String namespace, String podName) throws UnsupportedEncodingException {
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(new byte[128]);
        client.pods().inNamespace(namespace).withName(podName)
                .readingInput(byteArrayInputStream)
                .writingOutput(byteArrayOutputStream)
                .writingError(byteArrayOutputStream)
                .withTTY()
                .usingListener(new SimpleListener(countDownLatch))
                .exec("sh", "-c", "mysql-connector.sh");

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        final int size = byteArrayOutputStream.size();
        System.out.println("size = " + size);
        final String s = byteArrayOutputStream.toString("UTF-8");
        System.out.println("s = " + s);

        return null;
    }

    private static class SimpleListener implements ExecListener {

        private final CountDownLatch countDownLatch;

        private SimpleListener(CountDownLatch countDownLatch) {
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void onOpen() {
            System.out.println("The shell will remain open for 10 seconds.");
        }

        @Override
        public void onFailure(Throwable t, ExecListener.Response failureResponse) {
            countDownLatch.countDown();
            System.err.println("shell barfed");
        }

        @Override
        public void onClose(int code, String reason) {
            countDownLatch.countDown();
            System.out.println("The shell will now close.");
        }
    }

}
